package com.haierp.service.authority.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.mapper.authority.ResourceMapperHai;
import com.haierp.mapper.authority.RoleResourceMapperHai;
import com.haierp.model.authority.ResourceHai;
import com.haierp.service.authority.IResourceServiceHai;
import com.haierp.vo.authority.ResourceQueryVO;

/**
 * 
 * Title: ResourceServiceHaiImpl.java
 * Description: 
 *
 * @author jc
 * Apr 23, 2017
 *
 */
@Service("resourceServiceHai")
public class ResourceServiceHaiImpl extends SuperServiceImpl<ResourceMapperHai, ResourceHai> implements IResourceServiceHai {
    
	@Autowired
	private ResourceMapperHai iResourceMapperHai;
	
	@Autowired
	private RoleResourceMapperHai iRoleResourceMapperHai;

	@Override
	public Integer queryResourcesCount(ResourceQueryVO resourceQueryVO)
	{
		return iResourceMapperHai.queryResourcesCount(resourceQueryVO);
	}

	@Override
	public void deleteResourceById(Long id)
	{
		iResourceMapperHai.deleteById(id);
		
		List<Long> list = iRoleResourceMapperHai.queryIdListByResourceId(id);
		if (list != null && !list.isEmpty()) {
	        for (Long roleResourceId : list) {
	            iRoleResourceMapperHai.deleteById(roleResourceId);
	        }
	    }
	}
	
	@Override
	public List<ResourceHai> queryResourceList()
	{
        EntityWrapper<ResourceHai> wrapper = new EntityWrapper<ResourceHai>();
        wrapper.orderBy("seq");
        return iResourceMapperHai.selectList(wrapper);
	}

	@Override
	public List<ResourceHai> queryResourceTree(Long pid) {
		List<ResourceHai> listParent = queryResourceByPid(pid);
		
		if ((null != listParent) && (listParent.size() > 0)) {

			listParent.forEach(resourceHai -> {
				resourceHai.setChildList(queryResourceTree(resourceHai.getId()));
			});
		}
		
		return listParent;
	}
	
	/**
	 * 递归调用获取子级资源
	 * @param pid
	 * @return
	 */
    private List<ResourceHai> queryResourceByPid(Long pid) {
        EntityWrapper<ResourceHai> wrapper = new EntityWrapper<ResourceHai>();
        ResourceHai resource = new ResourceHai();
        wrapper.setEntity(resource);
        if (null == pid) {
            wrapper.where("pid is null", pid);
		} else {
	        wrapper.where("pid = {0}", pid);
		}
        wrapper.orderBy("seq");
        return iResourceMapperHai.selectList(wrapper);
    }
}